package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.oss.AliyunOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * deviceService业务层处理
 *
 * @author gyf
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询device
     *
     * @param id device主键
     * @return device
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询device列表
     *
     * @param device device
     * @return device
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增device
     *
     * @param device device
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改device
     *
     * @param device device
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(Device device) {
        //先修改数据库
        int i = deviceMapper.updateById(device);
        //在修改iot
        //调用iot提供的修改方法
        BatchUpdateDeviceNicknameRequest nicknameRequest = new BatchUpdateDeviceNicknameRequest();
        nicknameRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceNicknameInfos = new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceNicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();

        //封装数据到集合中
        deviceNicknameInfo.setProductKey(device.getProductKey());
        deviceNicknameInfo.setDeviceName(device.getDeviceName());
        deviceNicknameInfo.setNickname(device.getNickname());
        deviceNicknameInfos.add(deviceNicknameInfo);

        nicknameRequest.setDeviceNicknameInfo(deviceNicknameInfos);

        BatchUpdateDeviceNicknameResponse response;
        try {
             response = client.batchUpdateDeviceNickname(nicknameRequest);
        } catch (Exception e) {
            throw new BaseException("修改设备备注失败");
        }

        if (!response.getBody().getSuccess()){
            throw new BaseException("修改设备备注失败");
        }

        return i;
    }

    /**
     * 批量删除device
     *
     * @param ids 需要删除的device主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除device信息
     *
     * @param id device主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 同步产品列表到redis
     */
    @Override
    public void syncProductList() {
        //从IoT平台查询产品列表
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(100);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();

        //把产品列表保存到redis中

        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSON.toJSONString(productInfo));
    }

    /**
     * 从redis中取出产品
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //读取redis中产品列表
        String s = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if (StringUtils.isEmpty(s)) {
            return List.of();
        }
        //返回VO对象
        return JSON.parseArray(s, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称是否重复

        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2.如果不重复,则进行注册设备到阿里云IoT平台
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        //产品id
        registerDeviceRequest.setProductKey(deviceDto.getProductKey());
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;

        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("注册设备到阿里云IoT失败");
        }

        if (!response.getBody().getSuccess()) {
            throw new BaseException("注册设备到阿里云IoT失败");
        }

        //3.判断设备的位置,如果是 随身设备0,则物理位置为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //4.再把设备保存到数据库中
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //注入IoT_id
        String iotId = response.getBody().getData().getIotId();
        device.setIotId(iotId);
        try {
            int insert = deviceMapper.insert(device);
            if (insert == 0) {
                deleteDevice(deviceDto, iotId);
                throw new BaseException("设备添加到数据库失败");
            }
        } catch (Exception e) {
            deleteDevice(deviceDto, iotId);
            throw new BaseException("设备添加到数据库失败");
        }
    }

    /**
     * 删除阿里云IoT平台中的设备
     *
     * @param deviceDto
     * @param iotId
     */
    private void deleteDevice(DeviceDto deviceDto, String iotId) {
        //删除阿里云IoT平台中的设备
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setIotId(iotId);
        deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
        String deviceName = deviceDto.getDeviceName();
        deleteDeviceRequest.setDeviceName(deviceName);
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception ex) {
            throw new BaseException("删除阿里云设备" + deviceName + "失败");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //从IoT平台查看设备详情
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("查询iot设备详情失败");
        }

        if (!response.getBody().getSuccess()) {
            throw new BaseException("查询iot设备详情失败");
        }

        //封装数据到VO
        DeviceVo deviceVo = BeanUtil.toBean(response.getBody().getData(), DeviceVo.class);

        //从数据库查看设备详情
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));

        BeanUtil.copyProperties(device, deviceVo);
        return deviceVo;
    }

    /**
     * 查询物模型
     *
     * @param deviceDto
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(DeviceDto deviceDto) {
        QueryThingModelPublishedRequest request = new QueryThingModelPublishedRequest();
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("查询iot物模型失败");
        }

        if (!response.getBody().getSuccess()) {
            throw new BaseException("查询iot物模型失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("查询设备物模型运行状态失败");
        }

        if (!response.getBody().getSuccess()) {
            throw new BaseException("查询设备物模型运行状态失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 删除设备数据库以及iot
     *
     * @param device
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDevice(Device device) {
        //先删数据库
         deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, device.getIotId())
                 .eq(Device::getProductKey,device.getProductKey()));

        try {
            //再删iot
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.setProductKey(device.getProductKey());
            request.setIotId(device.getIotId());
            request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除iot设备失败");
        }
    }
}
